package me.xue.communityhealth.service;

import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import me.xue.communityhealth.exception.ObjectNotFoundException;
import me.xue.communityhealth.model.User;
import me.xue.communityhealth.repo.UserRepository;
import me.xue.communityhealth.util.ApplicationUtil;
import me.xue.communityhealth.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@Service
@Slf4j
public class UserService implements BaseService<User, Integer> {

    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public int save(User user) {
        return userRepository.save(user);
    }

    @Override
    public int update(User user) {
        return userRepository.update(user);
    }

    @Override
    public int delete(Integer which) {
        return userRepository.delete(which);
    }

    @Override
    public List<User> findAll() {
        return null;
    }

    public User findOne(Integer id) {
        User user = userRepository.findOne(id);
        if (user == null) {
            throw new ObjectNotFoundException();
        }
        return user;
    }

    public String savePortrait(MultipartFile multipartFile, String fileName) {
        if (multipartFile != null && !multipartFile.isEmpty()) {
            return FileUtil.saveMultipartFile(multipartFile, ApplicationUtil.getPortraitPath().getAbsolutePath(), fileName);
        }
        return null;
    }

    public void deletePortrait(String fileName) {
        File file = new File(ApplicationUtil.getPortraitPath().getPath(), fileName);
        if (file.exists()) {
            try {
                Files.delete(Paths.get(ApplicationUtil.getPortraitPath().getPath(), fileName));
            } catch (IOException e) {
                log.error("删除用户图片失败", e);
            }
        }
    }

    public Page<User> pagedUsers() {
        return userRepository.pagedUsers();
    }
}
